﻿using System;
using System.Threading.Tasks;

namespace Miao
{
    public abstract class Handle
    {
        /// <summary>
        /// Called when Stopped.
        /// </summary>
        public event Action onStopped;
        /// <summary>
        /// Called when Finished (Whether completed or stoped).
        /// </summary>
        public event Action onFinished;

        public bool running { get; protected set; } = true;
        TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
        /// <summary>
        /// Stop
        /// </summary>
        public void Stop()
        {
            if (running)
            {
                running = false;
                onStopped?.Invoke();
                Finish();
                return;
            }
        }

        internal void Finish()
        {
            tcs.SetResult(true);
            onFinished?.Invoke();
            onFinished = null;
            onStopped = null;
            running = false;
        }
        /// <summary>
        /// 使用Complete等待时需拥有Stop逻辑来停止更新句柄！
        /// </summary>
        /// <returns></returns>
        public async Task Complete()
        {
            await tcs.Task;
        }

    }
}